﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceFacade.KDServiceClient.User;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.ServicesStub;
using Kingdee.K3.FIN.App.Core.Match;
using Kingdee.K3.FIN.Contracts;
using Kingdee.K3.FIN.Core;
using Kingdee.K3.FIN.Core.Match.Object;
using Kingdee.K3.FIN.Core.Parameters;
using Kingdee.K3.FIN.ServiceHelper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiMinCRMPlugin.VerificationApi
{
    /// <summary>
    /// 手工核销API
    /// </summary>
    [Description("反核销API")]
    [HotUpdate]
    public class AntiCancellationApi : AbstractWebApiBusinessService
    {
        //固定写法,GetCust和上面类名称一致
        public AntiCancellationApi(KDServiceContext context)
            : base(context)
        {
        }
        //接收Json, 返回JObject
        public string ExecuteService(string parameter)
        {
            //        {
            //            "parameter": {
            //                "UserId": 100256,
            //    "MatchFIDList": [
            //        111340,
            //        111341
            //                ]
            //}
            //        }

            //解析传入JSON
            Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(parameter);
            int UserId = Convert.ToInt32(dicJson["UserId"].ToString());
            //将data数据部分转换为JsonArray对象
            JArray datArray = JArray.Parse(dicJson["MatchFIDList"].ToString());

            string Result;
            //调用核销方法
            IOperationResult operationResult = AntiCancellation(UserId, datArray);
            if (operationResult.IsSuccess)
            {
                Result = JsonConvert.SerializeObject(operationResult.OperateResult);
            }
            else
            {
                Result = JsonConvert.SerializeObject(operationResult.ValidationErrors);
            }
            return Result;



        }




        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="Desc">错误描述</param>
        /// <param name="DName">操作名称</param>
        /// <param name="BillName">单据名称</param>
        /// <param name="subID">领域编号</param> 应付单=50
        /// <returns></returns>
        public bool GetLog(string Desc, string DName, string BillName, string subID)
        {
            bool Judge = false;
            try
            {
                //保存上机日志
                var logs = new List<LogObject>();
                var log = new LogObject();
                log.pkValue = BillName;
                log.Description = Desc;
                log.OperateName = DName;
                log.ObjectTypeId = "";
                log.SubSystemId = subID;
                log.Environment = OperatingEnvironment.BizOperate;
                logs.Add(log);
                LogServiceHelper.BatchWriteLog(this.KDContext.Session.AppContext, logs);
                //保存文档日志
                Logger.Info(BillName + "-" + DName, Desc);
                Logger.Error(BillName + "-" + DName, Desc, new KDException("?", "金蝶异常......"));
                var logFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\Cloud.log";
                Judge = true;
            }
            catch (Exception)
            {
            }
            return Judge;
        }




        /// <summary>
        /// 反核销接口调用
        /// </summary>
        /// <param name="UserId">用户ID</param>
        /// <param name="MatchFIDList">反核销数据</param>
        /// <returns></returns>
        public IOperationResult AntiCancellation(int UserId, JArray MatchFIDList)
        {
            //构造核销参数
            var para = new MatchParameters
            {
                MatchType = "3",      // 核销类型 
                UserId = UserId,
                IsUnMatch = true,
                InnerClear = false,
                WriteOff = false,
                ReversedOperationType = 3
            };
            para.CallBillInfo.Add("FVERIFYSEQ", new List<long>());
            para.IsBadDebtRecover = true;
            foreach (var item in MatchFIDList)
                para.CallBillInfo["FVERIFYSEQ"].Add(Convert.ToInt64(item.ToString()));
            // 引用 Kingdee.K3.FIN.ServiceHelper.dll
            // Kingdee.K3.FIN.Core.dll
            var operationResultR = MatchServiceHelper.UnMatch(this.KDContext.Session.AppContext, para);
            return operationResultR;
        }


    }
}
